package com.zn.services.impl;

import com.zn.common.exception.MyException;
import com.zn.common.utils.MD5Util;
import com.zn.dao.UserInfoMapper;
import com.zn.dao.UserRoleRelationMapper;
import com.zn.dto.UserDTO2;
import com.zn.dto.UserDTO3;
import com.zn.pojo.UserInfo;
import com.zn.pojo.UserRoleRelation;
import com.zn.services.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserRoleRelationMapper userRoleRelationMapper;


    @Override
    public UserInfo findUserByUN(String username) {
        return userInfoMapper.selectByUsername(username);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean insertUserInfo(UserDTO3 user) {
        UserInfo userInfo = new UserInfo();
        String password = MD5Util.Md5(user.getUsername(), user.getPassword());
        userInfo.setCreateTime(new Date());
        userInfo.setImei("123");
        userInfo.setUsername(user.getUsername());
        userInfo.setPassword(password);
        userInfo.setHolder(user.getHolder());
        int flag1;
        int flag2;
        try {
            flag1 = userInfoMapper.insertSelective(userInfo);
            UserRoleRelation relation = new UserRoleRelation();
            relation.setRoleId(user.getRoleId());
            relation.setRoleName(user.getRoleName());
            relation.setUserId(userInfo.getUserId());
            flag2 = userRoleRelationMapper.insertSelective(relation);
            if (flag1 == 0 || flag2 == 0) {
                throw new RuntimeException();
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
            log.error("注册失败!",e.getMessage());
            throw new MyException(605,"注册失败!");
        }catch (Exception e){
            e.printStackTrace();
            throw new MyException(605,e.getMessage());
        }
        return true;
    }

    @Override
    public UserRoleRelation findUserAuthByUid(Integer uid) {
        return userRoleRelationMapper.selectRoleRelationByUid(uid);
    }

    @Override
    public int updatePassword(Integer uid,String password) {
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(uid);
        String s = MD5Util.Md5(userInfo.getUsername(), password);
        return userInfoMapper.updateUserPassword(uid,s);
    }

    @Override
    public List<UserDTO3> getAll() {
        return userInfoMapper.selectAll();
    }

    @Override
    public List<UserDTO3> getByRoleId(int roleId) {
        return userInfoMapper.selectByRoleId(roleId);
    }
}
